<template>
    <div class="ui container">
        <div v-if="articalData.length" class="ui grid">
            <post :excerpt="item.excerpt" :likesNum="item.likeNum" 
                :commentsNum="item.commentNum" :title="item.title" :avatar="item.info.avatar" :nickname="item.info.nickname"
                :imgURL="item.imgURL" :createdTime="moment(item.createdTime).format('YYYY-MM-DD HH:mm:ss')" 
                :aid="item._id" @refresh="getMyPosts(pagination.pageSize, pagination.pageNum)" 
                v-for="(item, index) in articalData" :key="index" type="square"></post>
                <div class="centered row">
                    <el-pagination layout="prev , pager,  next" :total="pagination.total" :page-size="pagination.pageSize"
                                :page-count="pagination.pageNum" @current-change="getMyPosts(pagination.pageSize, pagination.pageNum)" ></el-pagination>
                </div>
        </div>
        <div v-else>暂无文章</div>
    </div>
</template> 
<script>
import Post from '@/components/post'
import {api_artical, serverAssetsRoot} from '@/api'
export default {
    activated () {
        this.getMyPosts(this.pagination.pageSize, this.pagination.pageNum)
        console.log('activated', this.url)
    },
    components: {
        Post
    },
    data () {
        return {
            articalData: [],
            pagination: {
                pageSize: 20,
                pageNum: 1,
                total: 0
            }
        }
    },
    methods: {
        getMyPosts (pageSize, pageNum) {
            this.$http({
                method: 'get',
                url: api_artical + (this.url ? this.url : '/all'),
                params: {
                    page_size: pageSize,
                    page_index: pageNum
                }
            })
            .then(res => {
                this.postsDataAdapter(res.data.data)
                this.articalData = res.data.data
                this.pagination.total = res.data.total
            })
        },
        postsDataAdapter (data) {
            for (const post of data) {
                post.info.avatar = serverAssetsRoot + post.info.avatar

                var containerDOM = document.createElement('div')
                containerDOM.innerHTML = post.content
                if (containerDOM.getElementsByTagName('img').length) {
                    console.log('has img tag', containerDOM.getElementsByTagName('img'))
                    post.imgURL = containerDOM.getElementsByTagName('img')[0].src
                }
            }
        }
    },
    props: {
        url: String
    }
}
</script>
<style lang="stylus" scoped>

</style>
